#pragma once

#include "button.h"

class RGBControl : public Button
{
	BitMaP * m_bmp;
	int * m_controlledColor;
	int m_index;
	char m_text[4];
	RGB_QUAD m_color, m_borderColor;
public:
	RGB_QUAD * getControlledColor(){return m_bmp->getColor(*m_controlledColor);}
	// TODO name something less weird
	unsigned char * getColorDimensionValue(){return getControlledColor()->getValue(m_index);}
	void updateColor(const unsigned char a_value)
	{
		sprintf_s(m_text, sizeof(m_text), "%02X", a_value);
		*m_color.getValue(m_index) = a_value;
		if(m_parent)
		{
			m_parent->getParent()->setDirty(0);
		}
	}
	void refresh()
	{
		updateColor(*getColorDimensionValue());
	}
	/**
	 * @param a_colorIndexReference where in memory the color index will be stored
	 */
	void setRGBControl(int * a_colorIndexReference, const int & a_R_G_or_B, BitMaP * a_bmp)
	{
		m_bmp = a_bmp;
		m_controlledColor = a_colorIndexReference;
		m_index = a_R_G_or_B;
		*m_borderColor.getValue(m_index) = RGB_QUAD::MAX_COMPONENT_VALUE;
		updateColor(*getColorDimensionValue());
	}
	virtual void draw(SDL_Surface * a_screen)
	{
		SRect dim(*getArea());
		dim.w = dim.h;
		int border = 2;
		VSDL_drawRect(a_screen, &dim, 
			RGBQUAD_toSurfaceColor(m_borderColor, a_screen->format), border);
		dim.inset(border);
		SPoint textLoc(dim.getMaxX()+border*2, dim.getMinY());
		VSDL_FillRect(a_screen, &dim, RGBQUAD_toSurfaceColor(m_color, a_screen->format));
		VSDL_drawString(m_text, a_screen, textLoc);
		//setClean();
	}
	RGBControl():m_bmp(0),m_controlledColor(0),m_index(0){}
	virtual bool handleEvent(const SDL_Event & a_event)
	{
		bool handled = false;
		bool dirty = false;
		switch(a_event.type)
		{
		case SDL_MOUSEBUTTONDOWN:
			switch(a_event.button.button)
			{
			case SDL_BUTTON_WHEELUP:
			case SDL_BUTTON_WHEELDOWN:
				{
					unsigned char * value = getColorDimensionValue();
					if(value)
					{
						*value += (a_event.button.button==5)?-1:1;
						updateColor(*value);
					}
				}
				dirty = true;
				break;
			}
		}
		if(!handled)
		{
			handled = Button::handleEvent(a_event);
		}
		if(dirty)
		{
			setDirty(0);
			m_parent->setDirty(0);
		}
		return handled || dirty;
	}
};